package com.umgsai.wx.backend.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections4.MapUtils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtil {

    private final static OkHttpClient okHttpClient = new OkHttpClient.Builder().
            connectTimeout(20, TimeUnit.SECONDS).
            readTimeout(20, TimeUnit.SECONDS).
            build();

    /**
     * 同步post请求，无header参数
     *
     * @param url
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, Object> paramMap) throws Exception {
        String uuid = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        String result = null;
        try {

//            log.info("http.post请求开始, uuid={}, start={}, url={}", uuid, start, url);
            RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(paramMap));

            final Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
//            log.info("http.post请求结束, uuid={}, end={}, cost={}, url={}, paramMap={}, result={}", uuid, end, end - start, url, JSON.toJSONString(paramMap), result);
        }
    }

    public static String post(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws Exception {
        String uuid = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        String result = null;
        try {

            log.info("http.post请求开始, uuid={}, start={}, url={}", uuid, start, url);
            RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(paramMap));

            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .post(requestBody);

            if (MapUtils.isNotEmpty(headerMap)) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }

            Request request = builder.build();

            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
            }
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            log.info("http.post请求结束, uuid={}, end={}, cost={}, url={}, paramMap={}, result={}", uuid, end, end - start, url, JSON.toJSONString(paramMap), result);
        }
    }

    public static String get(String url) throws Exception {
        String uuid = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        String result = null;
        try {

            log.info("http.get请求开始, uuid={}, start={}, url={}", uuid, start, url);

            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
            }

            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            log.info("http.get请求结束, uuid={}, end={}, cost={}, url={}, result={}", uuid, end, end - start, url, result);
        }
    }

    public static String get(String url, Map<String, String> headerMap) throws Exception {
        String uuid = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        String result = null;
        try {

//            log.info("http.get请求开始, uuid={}, start={}, url={}", uuid, start, url);

            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .get();

            if (MapUtils.isNotEmpty(headerMap)) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }

            Request request = builder.build();

            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
            }

            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
//            log.info("http.get请求结束, uuid={}, end={}, cost={}, url={}, result={}", uuid, end, end - start, url, result);
        }
    }

    public static String get(String url, Map<String, String> headerMap, Map<String, String> paramMap) throws Exception {
        String uuid = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        String result = null;
        try {


            StringBuilder paramString = new StringBuilder();
            if (MapUtils.isNotEmpty(paramMap)) {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    String name = entry.getKey();
                    String value = entry.getValue();
                    if (paramString.length() > 0) {
                        paramString.append("&");
                    }
                    paramString.append(name);
                    paramString.append("=");
                    paramString.append(value);
                }
            }
            url = url + "?" + paramString;
            log.info("http.get请求开始, uuid={}, start={}, url={}", uuid, start, url);
            Request.Builder builder = new Request.Builder()
                    .url(url)
                    .get();

            if (MapUtils.isNotEmpty(headerMap)) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }

            Request request = builder.build();

            final Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            ResponseBody body = response.body();
            if (body != null) {
                result = body.string();
            }

            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            long end = System.currentTimeMillis();
            log.info("http.get请求结束, uuid={}, end={}, cost={}, url={}, result={}", uuid, end, end - start, url, result);
        }
    }
}